package com.example.a2205douyin;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.a2205douyin.baseMVVM.view.BaseActivity;
import com.example.a2205douyin.databinding.ActivityMainBinding;
import com.example.a2205douyin.entity.UserEntity;
import com.example.a2205douyin.login.LoginViewModel;
import com.example.a2205douyin.register.RegisterActivity;

public class MainActivity extends BaseActivity<ActivityMainBinding, LoginViewModel> {


    @Override
    protected void initData() {
        viewModel.success.observe(this, new Observer<UserEntity>() {
            @Override
            public void onChanged(UserEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){//登录成功
                    //判断记住密码是否被选中，如果被选中，将用户名密码保存到SP中
                    SPUtils.getInstance().put("username",entity.getData().getUsername());
                    SPUtils.getInstance().put("password",entity.getData().getPassword());
                    SPUtils.getInstance().put("token",entity.getData().getToken());
                    SPUtils.getInstance().put("icon",entity.getData().getIcon());
                    if(binding.cb.isChecked()){
                        //选中状态也可以记录一下
                        SPUtils.getInstance().put("isChecked",true);
                    }else{
                        SPUtils.getInstance().put("isChecked",false);
                    }
                    //跳转到主页中
                    startActivity(new Intent(MainActivity.this,DouyinActivity.class));
                }
            }
        });
        viewModel.fail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
    }

    @Override
    protected void initView() {
        binding.login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.login(binding.etUsername.getText().toString(),binding.etPassword.getText().toString());
            }
        });
        boolean checked = SPUtils.getInstance().getBoolean("isChecked", false);
        binding.cb.setChecked(checked);
        //点击文字，跳转到注册界面
        binding.goRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, RegisterActivity.class));
            }
        });

    }

    @Override
    protected Class<LoginViewModel> getViewModel() {
        return LoginViewModel.class;
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }
}